/**
 * 
 */
package de.tum.in.eist.im.server;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import de.tum.in.eist.im.client.ChatServiceBeta;
import de.tum.in.eist.im.client.domain.Message;
import de.tum.in.eist.im.client.domain.NewMessagesChunk;
import de.tum.in.eist.im.client.domain.User;

/**
 * @author Michael Koepferl
 *
 */
public class ChatServiceBetaImpl extends RemoteServiceServlet implements ChatServiceBeta {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5556348051465659719L;
	private List<User> registeredUsers = new ArrayList<User>();
	private NewMessagesChunk chunk = new NewMessagesChunk();
	private List<User> loggedinUsers = new ArrayList<User>();
	private List<Message> messageList = new ArrayList<Message>();
	/**
	 * 
	 */
	public ChatServiceBetaImpl() {
		// TODO Auto-generated constructor stub
		
	}
	public List<User> getLoggedInUsers() {
		return loggedinUsers;
	}
	public List<Message> getHistory(long d) {
		List<Message> lm = messageList;
		return lm;
	}
	/**
	 * Sends the new messages to the client, as he asks for them
	 */
	public NewMessagesChunk getNewMessages(long t) {
		NewMessagesChunk c = new NewMessagesChunk();
		List<Message> lm = new ArrayList<Message>();
		c.setTimestamp(new Date().getTime());
		for(int i=0;i<messageList.size();i++) {
			if(messageList.get(i).getTimestamp()>t) {
				lm.add(messageList.get(i));
			}
		}
		c.setMessages(lm);
		return c;
	}
	public boolean login(User u) {
		//TODO Condition for successful login
		// not for alpha version
		String user=u.getUsername();
		String pass=u.getPassword();
		if(false) { // insert condition for successful login here = password matches username's password in database
			return false;
		}
		loggedinUsers.add(u);
		return true;
	}
	public boolean logout(User u) {
		loggedinUsers.remove(u);
		//nothing can go wrong
		return true;
	}
	public boolean registerNewUser(User u) {
		Window.alert("Registration not implemented");
		return false;
	}
	public void sendMessage(Message m) {
		messageList.add(m);
		System.out.println("Message sent successfully");
	}
 	

}
